package com.fandou.airobot.ui.widget.voice;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.MediaRecorder;
import android.util.AttributeSet;

import com.fandou.airobot.R;

/**
 * @author zdxiang
 * @date 2020/7/9 15:54
 */
public class VoiceButton extends androidx.appcompat.widget.AppCompatImageView {

    private Context mContext;

    //存储很多张话筒图片的数组
    private Drawable[] micImages;

    private static final int BASE = 600;

    private static final int SPACE = 200;// 间隔取样时间

    private MediaRecorder recorder = null;

    public VoiceButton(Context context) {
        super(context);
        init(context);
    }

    public VoiceButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }


    public VoiceButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
//        if (context instanceof AppCompatActivity) {
//            ((AppCompatActivity) context).getLifecycle().addObserver(this);
//        }
        // 动画资源文件,用于录制语音时
        micImages = new Drawable[]{
                getResources().getDrawable(R.drawable.volume_0),
                getResources().getDrawable(R.drawable.volume_1),
                getResources().getDrawable(R.drawable.volume_2),
                getResources().getDrawable(R.drawable.volume_3),
                getResources().getDrawable(R.drawable.volume_4),
                getResources().getDrawable(R.drawable.volume_5),
        };
        setImageDrawable(micImages[0]);
    }

    private int mCurrentBar;

    // 使音量下降效果变平和
    private static final int BAR_DROPOFF_STEP = 1;

    /**
     * @param volume 以下算法参考自百度sdk SDKAnimationView.java
     */
    public void updateMicStatus(int volume) {
        int min = 0;
        int max = 5;
        int bar = min;
        bar += (int) (max - min) * volume / 200;
        if (bar > mCurrentBar) {
            mCurrentBar = bar;
        } else {
            mCurrentBar = Math.max(bar, mCurrentBar - BAR_DROPOFF_STEP);
        }
        mCurrentBar = Math.min(max, mCurrentBar);

        setImageDrawable(micImages[mCurrentBar]);
    }

}
